package com.czxy.demo01;

import cn.itcast.servlet.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet("/cookie")
public class CookieServlet extends BaseServlet {

    public void url1() throws IOException {

        Cookie ck = new Cookie("url1", new Date().getTime() + "");
        getResponse().addCookie(ck);
        getResponse().getWriter().write("欢迎访问url1");

    }

    public void url2() throws IOException {

        Cookie ck = new Cookie("url2", new Date().getTime() + "");
        getResponse().addCookie(ck);
        getResponse().getWriter().write("欢迎访问url2");

    }

    public void url3() throws IOException {

        Cookie ck = new Cookie("url3", new Date().getTime() + "");
        getResponse().addCookie(ck);
        getResponse().getWriter().write("欢迎访问url3");

    }

    public Cookie getCookie(Cookie[] cookies, String name) {
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }
        }
        return null;
    }

    public void views() throws IOException {
        List<Cookie> list = new ArrayList<>();
        Cookie[] cookies = getRequest().getCookies();
        Cookie url1 = getCookie(cookies, "url1");
        Cookie url2 = getCookie(cookies, "url2");
        Cookie url3 = getCookie(cookies, "url3");

        if (url1 != null) {
            list.add(url1);
        }
        if (url2 != null) {
            list.add(url2);
        }
        if (url3 != null) {
            list.add(url3);
        }

        list.sort((o1, o2) -> o2.getValue().compareTo(o1.getValue()));

        StringBuffer sb = new StringBuffer();

        for (Cookie ck : list) {
            sb.append(ck.getName()).append(" 浏览时间 ").append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(ck.getValue())))).append("<br>");
        }

        getResponse().getWriter().write(sb.toString());

    }

    public void clean() throws IOException {
        // 1.创建 三个cookie 设置生命周期为 0
        Cookie ck1 = new Cookie("url1", "");
        Cookie ck2 = new Cookie("url2", "");
        Cookie ck3 = new Cookie("url3", "");

        ck1.setMaxAge(0);
        ck2.setMaxAge(0);
        ck3.setMaxAge(0);

        // 2.响应给客户端
        getResponse().addCookie(ck1);
        getResponse().addCookie(ck2);
        getResponse().addCookie(ck3);

        getResponse().getWriter().write("清除完毕");
    }
}
